package com.frame.pageform.tag;


import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CheckboxTag extends BaseHandlerTag{

	private String bind;
	private String text;
	private String value;
	private String[] match;

	public int start() throws Exception
	{
		String s="<label class=\"radioButton\"><input name=\""+bind+"\" type=\"checkbox\" value=\""+value+"\"";
		Object obj=executeExpression(bind);
		if(obj!=null){
			if(obj.getClass().isArray()){
				try{
					int n=Array.getLength(obj);
					match=new String[n];
					for(int i=0;i<Array.getLength(obj);i++){
						match[i]=Array.get(obj, i).toString();
					}
				}catch(Exception e){throw new Exception(bind+"不支持多层复杂的数组结构数据",e);}
			}else if(obj instanceof List){
				List list=(List)obj;
				match=(String[])list.toArray(new String[list.size()]);
			}else if(obj instanceof Map){
				try{
					Map map=(Map)obj;
					Set set=map.keySet();
					Object[] objs=(Object[])set.toArray().clone();
					match=new String[objs.length];
					for(int i=0;i<objs.length;i++){
						match[i]=map.get(objs[i]).toString();
					}
				}catch(Exception e){throw new Exception(bind+"不支持多层复杂的Map结构数据",e);}
			}else
				match=new String[]{obj.toString()};
		}

		if(isMatched(value))
			s+=" checked";
		s+="/>";
		s+=text+"</label>";
		write(s);
		return 0;
	}
	private boolean isMatched(String value)
	{
		if(match == null || value == null)
			return false;
		for(int i = 0; i < match.length; i++)
			if(value.equals(match[i]))
				return true;

		return false;
	}
	public String getBind() {
		return bind;
	}

	public void setBind(String bind) {
		this.bind = bind;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
}
